package com.lpy.service;

import com.lpy.spring.BeanPostProcessor;
import com.lpy.spring.Component;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.Proxy;

import java.lang.reflect.Method;

/**
 * @Description:
 * @author: LiuPengYu
 * @date 2024/11/16 16:03
 */
@Component
public class LpyPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(String beanName, Object bean) {
        if ("userService".equals(beanName)) {
            System.out.println("初始化之前");
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(String beanName, Object bean) {
        if ("userService".equals(beanName)) {
            System.out.println("初始化后");
            try {
                // 创建 Enhancer 对象
                Enhancer enhancer = new Enhancer();
                // 设置目标类
                enhancer.setSuperclass(UserService.class);
                // 设置拦截器
                enhancer.setCallback(new MyInterceptor());
                // 创建代理对象
                return enhancer.create();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return bean;
    }
}
